package pmsjc.dpi.psaudavel;


import java.util.ArrayList;
import java.util.HashMap;

import pmsjc.dpi.psaudavel.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class PA_GlicemiaActivity extends Activity {

	GridView grid_main;
	private stru_pessoa pesPAGlicemia;
	private BuscaWS busca;
	private boolean PAGlic_alterado = false;
	
	public String[] str =  new String[] {"0","0","0","0","0"};
	
	//public String[] str =  new String[] {"0","0","0"};	 
	//String[] str =  new String[] {"0","0"};
  	
	public void PreencheTabelaPA(){
		//Tabela: Pressão Arterial
				ListView list = (ListView) findViewById(R.id.lstPA);
		   	    		
		    	ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
		    	HashMap<String, String> map = new HashMap<String, String>();
		    	map.put("situacao", "Normal");
		    	map.put("sistolica", "até 120");
		    	map.put("diastolica", "até 80");
		    	mylist.add(map);

		    	map = new HashMap<String, String>();
		    	map.put("situacao", "Pré-hipertenséo");
		    	map.put("sistolica", "de 121 a 139");
		    	map.put("diastolica", "de 81 a 89");
		    	mylist.add(map);
		    	
		    	map = new HashMap<String, String>();
		    	map.put("situacao", "Hipertenséo");
		    	map.put("sistolica", ">= 140");
		    	map.put("diastolica", ">=90");
		    	mylist.add(map);
		    	
		    	ListAdapter mSchedule = new SimpleAdapter(this, mylist, R.layout.tabela3colunas,
		    	            new String[] {"situacao", "sistolica", "diastolica"}, new int[] {R.id.col1, R.id.col2, R.id.col3});
		    	list.setAdapter(mSchedule);
	}
	
	public void PreencheTabelaGlicemia(){
		
    	// Tabela: Glicemia
    	ListView listGlic = (ListView) findViewById(R.id.lstglicemia);
    	ArrayList<HashMap<String, String>> mylistGlic = new ArrayList<HashMap<String, String>>();
    	HashMap<String, String> mapGlic = new HashMap<String, String>();
    	
   
     	RadioButton rbtCasual = (RadioButton) findViewById(R.id.rbtCasual);
     	
     	
   //CASUAL
  	
     	if (rbtCasual.isChecked()){
     		mapGlic.put("situacao", "Normal");
	    	mapGlic.put("valor", "até 139");
	    	mylistGlic.add(mapGlic);
	    	
	    	mapGlic = new HashMap<String, String>();
	    	mapGlic.put("situacao", "Pré-diabetes");
	    	mapGlic.put("valor", "De 140 a 199");
	    	mylistGlic.add(mapGlic);
	
	     	mapGlic = new HashMap<String, String>();
	    	mapGlic.put("situacao", "Diabetes Mellitus");
	    	mapGlic.put("valor", ">= 200");
	    	mylistGlic.add(mapGlic);

	    	Log.v("Preenche Tabela", "Casual");
     	}else{ //JEJUM
		
			mapGlic.put("situacao", "Normal");
	    	mapGlic.put("valor", "até 99");
	    	mylistGlic.add(mapGlic);
	    	
	    	mapGlic = new HashMap<String, String>();
	    	mapGlic.put("situacao", "Pré-diabetes");
	    	mapGlic.put("valor", "De 100 a 125");
	    	mylistGlic.add(mapGlic);
	
	     	mapGlic = new HashMap<String, String>();
	    	mapGlic.put("situacao", "Diabetes Mellitus");
	    	mapGlic.put("valor", ">= 126");
	    	mylistGlic.add(mapGlic);
			
	    	Log.v("Preenche Tabela", "Jejum");
		}
		
    	ListAdapter mGlic = new SimpleAdapter(this, mylistGlic, R.layout.rows,
    	            new String[] {"situacao", "valor"}, new int[] {R.id.TRAIN_CELL, R.id.FROM_CELL});
    	listGlic.setAdapter(mGlic);
    	
    	
    	
	}
		
	public void InicializaDados(){
		Log.i("Click - Antropometria", "InicializaDados" );
	 	TextView txtsist= (TextView) findViewById(R.id.txtPAGlic_sistolica);
     	TextView txtdias = (TextView) findViewById(R.id.txtPAGlic_diastolica);
     	TextView resultadoPA = (TextView) findViewById(R.id.txtPAGlic_resultadopa); 
     	TextView glic = (TextView) findViewById(R.id.txtPAGlic_glicemia);
     	
     	 TextView txtResultado = (TextView) findViewById(R.id.txtresultpaglic);
   		 txtResultado.setText("");  
   		 
   		TextView txtdatasistema = (TextView) findViewById(R.id.txtdatasistemaGlicemia);   
   		 
     	
     	PAGlic_alterado = false;
     	
     	RadioGroup rgTeste = (RadioGroup) findViewById(R.id.rgpGlicemia);   
  		rgTeste.check(R.id.rbtCasual);
  		
     	PreencheTabelaPA();
     	PreencheTabelaGlicemia();
     	
     	
     	/*
     	<achou>string</achou>                 0
        <pCPF>long</pCPF>                     1
        <pPsauPamaxima>long</pPsauPamaxima>   2
        <pPsauPaminima>long</pPsauPaminima>   3
        <pGlicemiaTipo>string</pGlicemiaTipo> 4
        <pGlicemia>int</pGlicemia>            5
        <data_exame>string</data_exame>       6
        <data_sistema>string</data_sistema>   7
        */
     	
  		
	    busca = new BuscaWS();
	    //String[] str =  new String[] {"0","0"};
	    str = busca.BuscaPAGlicemia(PSaudavelActivity.pessoa.pessoa_cpf);
	    txtsist.setText(str[0]);
     	txtdias.setText(str[1]);
     	txtdatasistema.setText(str[4]);
	    
     	resultadoPA.setText("");
     	
     	
     	glic.setText(str[3]);
     	if (str[2].equals("JEJUM")) { rgTeste.check(R.id.rbtJejum);}
     	
     	
        ResultadoPAGlicemia(View.INVISIBLE);
	}
	
	public void ResultadoPAGlicemia(int mostra){
		LinearLayout lyt = (LinearLayout) findViewById(R.id.resultadopa);
		LinearLayout lytAbdomen = (LinearLayout) findViewById(R.id.resultadoglic);
   		lyt.setVisibility(mostra);
   		lytAbdomen.setVisibility(mostra);
	}
		
	@Override
	protected void onResume() {
			   
		    InicializaDados();
		    
		    retornaDataSistema();
		   
		    pesPAGlicemia  = PSaudavelActivity.pessoa;
		    		   
		
		super.onResume();

		Log.e("onResume", "Resume" );
	}
	
	public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.pa_glicemia);
    	
    	final TextView vsistolica = (TextView) findViewById(R.id.txtPAGlic_sistolica); 
    	final TextView vdiastolica = (TextView) findViewById(R.id.txtPAGlic_diastolica); 		
    	final TextView vvalor = (TextView) findViewById(R.id.txtPAGlic_glicemia); 
		
    	retornaDataSistema();
    	
    	vvalor.addTextChangedListener(new TextWatcher() {
			

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
	
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
	
			public void afterTextChanged(Editable s) {
				PAGlic_alterado = true;
				
			}
		});
    	
    	vdiastolica.addTextChangedListener(new TextWatcher() {
	
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
	
			public void afterTextChanged(Editable s) {
				PAGlic_alterado = true;
				
			}
		});
    	
    	vsistolica.addTextChangedListener(new TextWatcher() {
			

			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
		
			public void afterTextChanged(Editable s) {
				PAGlic_alterado = true;
				
			}
		});
    	
         RadioButton radio_casual = (RadioButton) findViewById(R.id.rbtCasual);
         final RadioButton radio_jejum = (RadioButton) findViewById(R.id.rbtJejum);
         
         radio_casual.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
		
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				PAGlic_alterado = true;
				
			}
		});
         
         radio_jejum.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
		
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				PAGlic_alterado = true;
				
			}
		});
         
         radio_casual.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                //CASUAL
            	Log.e("onResume", "radio_casual" );
                PreencheTabelaGlicemia();
            }
        });

         radio_jejum.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                //JEJUM
            	Log.e("onResume", "radio_jejum" );
            	 PreencheTabelaGlicemia();
            }
        });
    	
    	
    	Button btnSalvar = (Button) findViewById(R.id.btnGlicemia);
    	btnSalvar.setOnClickListener(new Button.OnClickListener(){

			public void onClick(View v) {
				
				if ((vsistolica.length()> 0) && (vdiastolica.length()>0) && (vvalor.length()>0)){
				
			  		Log.e("PAGlic_alterado", String.valueOf(PAGlic_alterado));  		
					
			  		if (PAGlic_alterado){		
						String[] paglic =  new String[] {vsistolica.getText().toString(),
				  				vdiastolica.getText().toString() ,
				  				(radio_jejum.isChecked() ? "JEJUM" : "CASUAL") ,
				  				vvalor.getText().toString() };
				  					Log.e("paglic", paglic.toString());
						String[] res = busca.GravaPAGlicemia(pesPAGlicemia.pessoa_cpf, paglic );						
					if (res[0]=="N"){
						Toast toast= Toast.makeText(getApplicationContext(),"Erro ao salvar PA/Glicemia!", Toast.LENGTH_SHORT);  							
		   				 toast.setGravity(Gravity.TOP, 0, 70);
		   				 toast.show();
					}else{
						CalculoGlicemia();
						CalculoPA();
					    ResultadoPAGlicemia(View.VISIBLE);
					    TextView txtResultado = (TextView) findViewById(R.id.txtresultpaglic);
				   		 txtResultado.setText("Dados da pressão e glicemia gravados com sucesso!");
					}
					    PAGlic_alterado = false;
					}else{
						CalculoGlicemia();
						CalculoPA();
					    ResultadoPAGlicemia(View.VISIBLE);
					    TextView txtResultado = (TextView) findViewById(R.id.txtresultpaglic);
				   		 txtResultado.setText("Dados da pressão e glicemia gravados com sucesso!");
					}
					
				}else{
					Toast toast= Toast.makeText(getApplicationContext(), "Preencha pressão sistólica, diastólica e glicemia!", Toast.LENGTH_SHORT);  							
	   				 toast.setGravity(Gravity.TOP, 0, 70);
	   				 toast.show();
            		
            	}
			}
    		
    	});
   
	}
	
	public void CalculoPA(){
		TextView sistolica = (TextView) findViewById(R.id.txtPAGlic_sistolica); 
		TextView diastolica = (TextView) findViewById(R.id.txtPAGlic_diastolica); 		
		TextView resultadoPA = (TextView) findViewById(R.id.txtPAGlic_resultadopa); 
	
		 double vlrMaxima =  Double.parseDouble(sistolica.getText().toString());   
		 double vlrMinima =  Double.parseDouble(diastolica.getText().toString());   
		 
		  String informacao = "Ainda não calculado";
		 
		 if ((vlrMaxima >=140) || (vlrMinima >= 90)){
			 informacao = "HIPERTENSÃO";
		 }else{
			 if ((vlrMaxima < 140 && vlrMaxima >= 121) || (vlrMinima > 80 && vlrMinima < 90)){
				 	 informacao = "PRÉ-HIPERTENSÃO";				 
			 }else if ((vlrMaxima <= 120) || (vlrMinima <= 80)){
				  informacao="NORMAL";
			 }
		 }
		                    
       	
       	resultadoPA.setText(String.valueOf(informacao));
       	Log.e("resultado PA", informacao);
	}
	
	
	public void retornaDataSistema(){
		
		TextView txtdatasistema = (TextView) findViewById(R.id.txtdatasistemaGlicemia);      
		String vDataSistema = str[4];
     	String vTexto = "Informação salva em: ";
     	
    	if (vDataSistema.equals("0")) {
     		txtdatasistema.setText(str[4].replace("0"," ")); }
     		else { 
     			String result = vTexto + vDataSistema;     			
     			txtdatasistema.setText(result);     			 
     			}
     	    	
	}

	public void CalculoGlicemia(){
		
		TextView valor = (TextView) findViewById(R.id.txtPAGlic_glicemia); 
		TextView txtpesoideal = (TextView) findViewById(R.id.txtPAGlic_resglicemia); 	
		RadioButton radio_casual = (RadioButton) findViewById(R.id.rbtCasual);
		 
                double vlr =  Double.parseDouble(valor.getText().toString());                        
                      
                String informacao = "Ainda não calculado";
                         
                
                if (radio_casual.isChecked()){
                	 //CASUAL
					  if (vlr <= 139){
	            		  informacao = "NORMAL";       
	            	  }else if (vlr > 139 && vlr < 200 ){
	            		  informacao = "PRÉ-DIABETES";   
	            	  }else if (vlr >= 200 ){
	            		  informacao = "DIABETES MELLITUS";   
	            	  }
                }else{
                	 if (vlr <= 99){
	            		  informacao = "NORMAL";       
	            	  }else if (vlr > 99 && vlr < 126 ){
	            		  informacao = "PRÉ-DIABETES";   
	            	  }else if (vlr >= 126 ){
	            		  informacao = "DIABETES";   
	            	  }
                }
                
                                           
                
                LinearLayout lyt = (LinearLayout) findViewById(R.id.resultadoglic);
        	    lyt.setVisibility(1);
                                
             	
             	txtpesoideal.setText(String.valueOf(informacao));
             
	}
	
}